package com.cygia.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cygia.common.Result;
import com.cygia.entity.User;
import com.cygia.mapper.UserMapper;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    UserMapper userMapper;

    /**
     * 查询用户
     *
     * @param pageNum  当前页码
     * @param pageSize 每页多少条
     * @param search   查询字符
     * @return page
     */
    @GetMapping("/page")
    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "5") Integer pageSize,
                              @RequestParam(defaultValue = "") String search) {
        LambdaQueryWrapper<User> wrapper = Wrappers.<User>lambdaQuery();
        if (!search.isEmpty() || search.length() > 0) {
            wrapper.like(User::getUsername, search);
        }
        Page<User> page = userMapper.selectPage(new Page<>(pageNum, pageSize), wrapper);
        System.out.println(page);
        return Result.success(page);
    }

    /**
     * 添加or更新用户
     *
     * @param user
     * @return
     */
    @PostMapping("/save")
    public Result<?> save(@RequestBody User user) {
        if (user == null) {
            return Result.error(0001, "用户不存在，创建失败！");
        }
        if (user.getUsername().isEmpty()) {
            return Result.error(0002, "用户名为空，创建失败！");
        }
        if (user.getId() != null) {
            System.out.println(user);
            userMapper.updateById(user);
            return Result.success(0, "--更新用户成功：" + user);
        } else {
            userMapper.insert(user);
            return Result.success(0, "--添加用户成功：" + user);
        }

    }

    /**
     * 删除用户
     */
    @DeleteMapping("/delUser/{id}")
    public Result<?> deleteUserById(@PathVariable Long id) {
        userMapper.deleteById(id);
        return Result.success(0, "--删除用户成功：" + id);
    }
}
